<?php

namespace app\api\controller\v2;

use app\api\controller\Common;
use app\api\model\Blacklist;
use think\Db;
use think\Request;

class Blindbox extends Common {
    /**
     * @var mixed
     */
    public $params = null;
    /**
     * @param Request $request
     */
    public function __construct(Request $request = null) {
        parent::__construct($request);
        $this->params = getRsaPostParamArr2();
    }

    public function draw()
    {
        if ($this->member['sex']=='女' && $this->member['realname_auth'] != 2) return $this->miss('需完成实名认证');
        $draw_records = Db::name('blind_box_draw')
                            ->where(['user_id'=>$this->member['id']])
                            ->column('blind_box_id');
        $blacklist = Blacklist::lists($this->member['id'], false, true);

        $config = Db::name('config_system')->where(['category'=>'blindbox'])->column('content','title');
        $config['day_limit'] = $config['day_limit'] ?? 5;
        $config['day_limit_vip'] = $config['day_limit_vip'] ?? 10;
        $count = Db::name('blind_box_draw')
                    ->where('user_id='.$this->member['id'].' or touser_id='.$this->member['id'])
                    ->whereTime('create_time', 'today')
                    ->count();

        $day_limit = $config['day_limit'];
        $privileges = Db::name('grade_noble')->column('privilege', 'grade');
        $timenow = time();
        if ($this->member['noble_grade'] && $this->member['noble_time'] > $timenow) {
            $privilege = explode(',', $privileges[$this->member['noble_grade']]);
            if (in_array(20, $privilege)) {
                $day_limit = $config['day_limit_vip'];
            }
        }

        if ($count >= $day_limit) {
            return $this->miss('今日(被)抽取已上限'.$day_limit);
        }

        $where = ['a.status'=>1, 'a.delete_time'=>0, 'u.sex'=>$this->member['sex']=='男'?'女':'男', 'u.delete_time'=>0];
        // $where = ['a.status'=>1, 'a.delete_time'=>0, 'u.sex'=>$this->member['sex']=='男'?'女':'男', 'u.delete_time'=>0];
        if (!empty($draw_records)) {
            $where['a.id'] = ['not in', $draw_records];
        }

        $limitUids = [];
        $waitdrawuids = Db::name('blind_box')->where(['state'=>0, 'status'=>1])->column('user_id');
        $drawuids = Db::name('blind_box_draw')->where(['user_id' => ['in', $waitdrawuids]])->whereTime('create_time', 'today')->column('count(*) count', 'user_id');
        $drawuids2 = Db::name('blind_box_draw')->where(['touser_id' => ['in', $waitdrawuids]])->whereTime('create_time', 'today')->column('count(*) count', 'touser_id');
        $drawuserinfo = Db::name('user')->where(['id'=>['in', $waitdrawuids]])->column('id,noble_grade,noble_time', 'id');
        foreach ($drawuserinfo as $key => $value) {
            $day_limit = $config['day_limit'];
            if ($value['noble_grade'] && $value['noble_time'] > $timenow) {
                $privilege = explode(',', $privileges[$value['noble_grade']]);
                if (in_array(20, $privilege)) {
                    $day_limit = $config['day_limit_vip'];
                }
            }

            if (($drawuids[$key] ?? 0) + ($drawuids2[$key] ?? 0) >= $day_limit) {
                $limitUids[] = $key;
            }
        }

        $limitUids = array_merge($limitUids, $blacklist);

        $where['a.user_id'] = ['not in', $limitUids];

        $data = Db::name('blind_box')
                    ->master()
                    ->alias('a')
                    ->join('user u', 'a.user_id=u.id')
                    ->where($where)
                    ->orderRaw('rand()')
                    ->field('a.*')
                    ->find();

        if (!$data) return $this->miss('暂无纸条可抽取');

        $draw_record = Db::name('blind_box_draw')->insertGetId([
            'user_id'=>$this->member['id'],
            'blind_box_id'=>$data['id'],
            'touser_id'=>$data['user_id'],
            'create_time'=>time(),
            'state'=>0
        ]);

        if (!$draw_record) return $this->miss('抽取失败,请稍后重试');
        Db::name('blind_box')->where(['id'=>$data['id']])->update(['state'=>1]);

        return $this->pass(['id'=>$data['id']]);
    }

    public function putin()
    {
        $content = $this->params['content'] ?? '';
        $images = $this->params['images'] ?? '';
        $test = $this->params['test'] ?? 0;
        $content=iconv("utf-8","gbk//IGNORE",$content);
        $content = mb_convert_encoding($content,'UTF-8','GBK');
        if (!$content) return $this->miss('请输入内容');
        if (mb_strlen($content) > 100) return $this->miss('内容限制长度100');

        if ($this->member['sex']=='女' && $this->member['realname_auth'] != 2) return $this->miss('需完成实名认证');

        $insert = ['user_id'=>$this->member['id'], 'content'=>$content, 'images'=>$images, 'create_time'=>time(), 'status'=>0, 'state'=>0];
        if ($test) {
            $insert['status'] = 1;
        }
        $res = Db::name('blind_box')->insertGetId($insert);

        if (!$res) return $this->miss('放入失败,请稍后重试');
        return $this->pass(['id'=>$res]);
    }

    public function putinlist()
    {
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $data = Db::name('blind_box')
                    ->where(['user_id'=>$this->member['id'],'delete_time'=>0])
                    ->page($page)
                    ->limit($pagesize)
                    ->order('id desc')
                    ->field('id,content,images,create_time,status,reason')
                    ->select();

        foreach ($data as &$value) {
            $value['images'] = $value['images'] ? explode(',', $value['images']) : [];
            $value['create_time'] = date('Y-m-d H:i', $value['create_time']);
            $value['content']=iconv("utf-8","gbk//IGNORE",$value['content']);
            $value['content'] = mb_convert_encoding($value['content'],'UTF-8','GBK');
        }

        return $this->pass($data);
    }

    public function delputin()
    {
        $id = $this->params['id'] ?? 0;
        $res = Db::name('blind_box')->where(['id'=>$id, 'user_id'=>$this->member['id'], 'delete_time'=>0])->update(['delete_time'=>time()]);
        if (!$res) return $this->miss('删除失败,请稍后重试');
        return $this->pass('删除成功');
    }

    public function drawReturn()
    {
        $id = $this->params['id'] ?? 0;
        $draw_record = Db::name('blind_box_draw')->where([
            'user_id'=>$this->member['id'],
            'blind_box_id'=>$id,
            'delete_time'=>0,
            'return_time'=>0,
            'state'=>0
        ])->update(['return_time'=>time()]);
        if (!$draw_record) return $this->miss('放回失败');
        Db::name('blind_box')->where(['id'=>$id])->update(['state'=>0]);
        return $this->pass('放回成功');
    }
    public function drawDele()
    {
        $id = $this->params['id'] ?? 0;
        $draw_record = Db::name('blind_box_draw')->where([
            'user_id'=>$this->member['id'],
            'blind_box_id'=>$id,
            'delete_time'=>0
        ])->update(['delete_time'=>time()]);
        if (!$draw_record) return $this->miss('删除失败');
        return $this->pass('删除成功');
    }

    public function drawRecords()
    {
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;
        
        $data = Db::name('blind_box_draw')
                    ->where(['delete_time'=>0, 'return_time'=>0, 'user_id'=>$this->member['id']])
                    ->page($page)
                    ->limit($pagesize)
                    ->order('id desc')
                    ->field('id,user_id,blind_box_id,touser_id,content,state,create_time')
                    ->select();

        if (empty($data)) return $this->pass($data);

        $tousers = Db::name('user')->where(['id'=>['in', array_column($data, 'touser_id')]])->column('name,head_portrait,sex,age','id');
        $boxs = Db::name('blind_box')->where(['id'=>['in', array_column($data, 'blind_box_id')]])->column('content,images','id');

        foreach ($data as &$value) {
            $value['create_time'] = date('Y-m-d H:i', $value['create_time']);
            $value['touser'] = $tousers[$value['touser_id']] ?? false;
            if (isset($boxs[$value['blind_box_id']])) {
                $boxs[$value['blind_box_id']]['images'] = $boxs[$value['blind_box_id']]['images'] ? explode(',', $boxs[$value['blind_box_id']]['images']) : [];
                $value['boxs'] = $boxs[$value['blind_box_id']];
            } else {
                $value['boxs'] = false;
            }
        }

        return $this->pass($data);
    }

    public function info()
    {
        $id = $this->params['id'] ?? 0;
        $data = Db::name('blind_box')->field('id,user_id,content,images,create_time')->find($id);
        if (!$data) return $this->miss('获取数据失败');
        $data['create_time'] = date('Y-m-d H:i', $data['create_time']);

        $data['self'] = $this->member['id'] == $data['user_id'];
        $data['images'] = $data['images'] ? explode(',', $data['images']) : [];

        if ($data['self']) {
            $draw_record = Db::name('blind_box_draw')->where(['blind_box_id'=>$id, 'state'=>1])->field('user_id,content,update_time')->find();
            if ($draw_record) {
                $draw_record['update_time'] = date('Y-m-d H:i', $draw_record['update_time']);
                $draw_record['user'] = _user_cache($draw_record['user_id'], 'name,age,sex,head_portrait');
            }
        } else {
            $draw_record = Db::name('blind_box_draw')->where(['user_id'=>$this->member['id'], 'blind_box_id'=>$id, 'delete_time'=>0])->field('user_id,content,update_time')->find();
            if (!$draw_record) return $this->miss('获取数据失败'); 
            $data['user'] = _user_cache($data['user_id'], 'name,age,sex,head_portrait');
            $draw_record['update_time'] = date('Y-m-d H:i', $draw_record['update_time']);
        }

        $data['draw_info'] = $draw_record ?? false;

        return $this->pass($data);
    }

    public function drawToChat()
    {
        $id = $this->params['id'] ?? 0;
        $content = $this->params['content'] ?? input('content/s', '');

        if (!$content) return $this->miss('请输入回复内容');
        if (mb_strlen($content) > 100) return $this->miss('回复内容限制长度100');
        if(is_hasNumber($content) || is_hasCnNumber($content)) return $this->miss('当前禁止发送数字');


        // 敏感词检测
        $contain = Db::name('filter_word')->where(['state' => 1])->column('name');
        foreach ($contain as $k => $v) {
            if (stripos($content, $v) !== false) $this->miss('消息含有敏感词"' . $v . '",请重新编辑发送');
        }
        $contain = Db::name('ban_word')->where(['state' => 1])->column('name');
        $maskArr = ['','*','**','***','****','*****'];
        foreach ($contain as $k => $v) {
            if (stripos($content, $v) !== false) {
                $content = str_replace($v, $maskArr[mb_strlen($v)]??'*', $content);
            }
        }


        $draw_record = Db::name('blind_box_draw')->master()->where(['user_id'=>$this->member['id'], 'blind_box_id'=>$id, 'delete_time'=>0])->find();
        $box = Db::name('blind_box')->find($id);

        if (!$draw_record) return $this->miss('获取数据失败'); 
        if ($draw_record['return_time']) return $this->miss('已放回,不可回复');
        if ($draw_record['state']) return $this->miss('请勿重复回复');


        $res = Db::name('blind_box_draw')->where(['id'=>$draw_record['id']])->update(['content'=>$content, 'state'=>1, 'update_time'=>time()]);
        if ($res) {
            $datas = [
                'userid'   => $this->member['id'],
                'touserid' => $draw_record['touser_id'],
                'type'     => 22,
                'content'  => $content,
                'data'     => json_encode(['id' => $id, 'content'=>mb_substr($box['content'], 0, 20)], JSON_UNESCAPED_UNICODE),
            ];

            $request = request();
            $url     = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';
            curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
            return $this->pass('发送成功');
        }
    }
}